package com.dfrz.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dfrz.entry.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {

    //根据 action 跳转到不同的方法里面
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {

        Result result=new Result();
        resp.setContentType("application/json; charset=UTF-8");
        String action = request.getParameter("action");
        if (action==null||"".equals(action)){
            result.setCode(-1);
            result.setMessage("action 必填");

            resp.getWriter().write(JSONObject.toJSONString(result));
        }

        Class cla = this.getClass();  //获取单前类
        try {
//            getDeclaredMethod 获取 单前类 具体方法对象
            Method method = cla.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            将全权限分开
            method.setAccessible(true);
//            调用 invoke
            method.invoke(this, request, resp);
        } catch (Exception e) {
            e.printStackTrace();

            result.setCode(-1);
            result.setMessage("方法不存在、或方法执行异常");
            resp.getWriter().write(JSONObject.toJSONString(result));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
